package zy.blue7.im.core.codec;


import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageCodec;
import zy.blue7.im.common.message.Header;
import zy.blue7.im.common.message.Message;
import zy.blue7.im.common.message.MessageInfo;
import zy.blue7.im.core.utils.SerializableUtils;

import java.util.List;

/**
 * @Author: blue7
 * @Date: 2022/2/27 18:19
 * @Version 1.0
 * @Description
 */
public class MessageInfoCodec extends ByteToMessageCodec<MessageInfo> {
    @Override
    protected void encode(ChannelHandlerContext channelHandlerContext, MessageInfo messageInfo, ByteBuf byteBuf) throws Exception {
        byteBuf.writeInt(messageInfo.getHeader().getVersion());
        byteBuf.writeInt(messageInfo.getHeader().getContentLength());
        byteBuf.writeBytes(messageInfo.getHeader().getSessionId().getBytes());


        byte[] contentBytes = SerializableUtils.serializable(messageInfo.getMessage());
        byteBuf.writeBytes(contentBytes);

    }

    @Override
    protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf, List<Object> list) throws Exception {
        /**
         * 读取版本号
         */
        int version = byteBuf.readInt();

        /**
         * 读取 内容长度
         */
        int contentLength = byteBuf.readInt();

        /**
         *
         * 获取版本号
         */
        byte[] sessionByte = new byte[4];
        byteBuf.readBytes(sessionByte);
        String sessionId = new String(sessionByte);

        Header header = Header.builder()
                .version(version)
                .contentLength(contentLength)
                .sessionId(sessionId)
                .build();


        byte[] content = new byte[contentLength];
        byteBuf.readBytes(content);

        Message message = (Message) SerializableUtils.dSerializable(content);

        MessageInfo messageInfo = new MessageInfo();
        messageInfo.setHeader(header);
        messageInfo.setMessage(message);

        list.add(messageInfo);
    }
}
